package com.ruoyi.business.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.core.util.ObjUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ruoyi.business.domain.FileAttachment;
import com.ruoyi.business.domain.PersonFile;
import com.ruoyi.business.domain.bo.PersonFileBo;
import com.ruoyi.business.domain.vo.DocDirectoryVo;
import com.ruoyi.business.domain.vo.PersonFileVo;
import com.ruoyi.business.mapper.DocDirectoryMapper;
import com.ruoyi.business.mapper.PersonFileMapper;
import com.ruoyi.business.service.IPersonFileService;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.page.TableDataInfo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 人员档案类型Service业务层处理
 *
 * @author xxyd
 * @date 2024-11-27
 */
@RequiredArgsConstructor
@Service
public class PersonFileServiceImpl implements IPersonFileService {

    private final PersonFileMapper baseMapper;
    private final DocDirectoryMapper docDirectoryMapper;

    /**
     * 查询人员档案类型
     */
    @Override
    public PersonFileVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询人员档案类型列表
     */
    @Override
    public TableDataInfo<PersonFileVo> queryPageList(PersonFileBo bo, PageQuery pageQuery) {
        MPJLambdaWrapper<PersonFile> lqw = buildQueryWrapper(bo);
        Page<PersonFileVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询人员档案类型列表
     */
    @Override
    public List<PersonFileVo> queryList(PersonFileBo bo) {
        MPJLambdaWrapper<PersonFile> lqw = buildQueryWrapper(bo);
        return baseMapper.selectJoinList(PersonFileVo.class, lqw);
    }

    private MPJLambdaWrapper<PersonFile> buildQueryWrapper(PersonFileBo bo) {
        Map<String, Object> params = bo.getParams();
        MPJLambdaWrapper<PersonFile> joinQueryWrapper = new MPJLambdaWrapper<>();
        joinQueryWrapper.selectAll(PersonFile.class)
                .selectFunc(() -> "if(count(%s) > 0, '已上传', '未上传')", FileAttachment::getId, PersonFileVo::getStatus)
                .leftJoin(FileAttachment.class, FileAttachment::getPersonFileId, PersonFile::getId)
                .eq(bo.getPersonId() != null, PersonFile::getPersonId, bo.getPersonId())
                .eq(bo.getFileTopType() != null, PersonFile::getFileTopType, bo.getFileTopType())
                .eq(bo.getFileType() != null, PersonFile::getFileType, bo.getFileType())
                .groupBy(PersonFile::getId)
                .orderByAsc(PersonFile::getFileTopType);
        return joinQueryWrapper;
    }

    /**
     * 新增人员档案类型
     */
    @Override
    public Boolean insertByBo(PersonFileBo bo) {
        PersonFile add = BeanUtil.toBean(bo, PersonFile.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改人员档案类型
     */
    @Override
    public Boolean updateByBo(PersonFileBo bo) {
        PersonFile update = BeanUtil.toBean(bo, PersonFile.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(PersonFile entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除人员档案类型
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public List<Tree<Long>> personFileTree(Long personId) {
        List<DocDirectoryVo> directoryList = docDirectoryMapper.selectVoList(new QueryWrapper<>());


        List<PersonFileVo> personFileVos = this.queryList(PersonFileBo.builder().personId(personId).build());

        for (PersonFileVo personFileVo : personFileVos) {
            DocDirectoryVo docDirectoryVo = new DocDirectoryVo();
            docDirectoryVo.setId(personFileVo.getId());
            docDirectoryVo.setParentId(personFileVo.getFileType());
            docDirectoryVo.setName(personFileVo.getName().concat("(" + DateUtil.formatDate(personFileVo.getFileFromTime())) + ")");
            docDirectoryVo.setStatus("1");
            docDirectoryVo.setFileFromTime(personFileVo.getFileFromTime());
            directoryList.add(docDirectoryVo);
        }

        return TreeUtil.build(directoryList, 0L, (entity, tree) -> {
            tree.setWeight(ObjUtil.isNotNull(entity.getFileFromTime()) ? entity.getFileFromTime().getTime() * -1 : 0L);
            tree.setId(entity.getId());
            tree.setParentId(entity.getParentId());
            tree.setName(entity.getName());
            tree.putExtra("disabled", ObjUtil.isNull(entity.getStatus()));
        });

    }
}
